<?php
/**
 * Leek - Zend Framework Components
 *
 * @category   Leek
 * @package    Leek_Application
 * @subpackage Resource
 * @author     Chris Jones <leeked@gmail.com>
 * @link       http://code.google.com/p/leek-zf-components/
 * @license    http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @version    $Id: Multidb.php 76 2009-10-28 17:53:42Z leeked $
 */

/**
 * Resource for setting up multiple database instances
 *
 * @uses       Zend_Application_Resource_ResourceAbstract
 * @category   Leek
 * @package    Leek_Application
 * @subpackage Resource
 * @author     Chris Jones <leeked@gmail.com>
 */
class Leek_Application_Resource_Multidb extends Zend_Application_Resource_ResourceAbstract
{
    /**
     * @uses Zend_Db_Adapter_Interface
     * @var array
     */
    protected $_dbAdapters = array();

    /**
     * Adds a Db Adapter to the stack
     *
     * @param string $dbName
     * @param Zend_Db_Adapter $dbAdapter
     * @return Leek_Application_Resource_Multidb
     */
    public function addDbAdapter($dbName, $dbAdapter)
    {
        if ($dbAdapter instanceof Zend_Db_Adapter_Abstract) {
            $this->_dbAdapters[$dbName][] = $dbAdapter;
        }

        return $this;
    }

    /**
     * Returns the Db Adapter stack
     *
     * @return array
     */
    public function getDbAdapters()
    {
        return $this->_dbAdapters;
    }

    /**
     * Defined by Zend_Application_Resource_Resource
     *
     * @return array
     */
    public function init()
    {
        $options = $this->getOptions();

        // Loop through each database name
        foreach ($options as $dbName => $dbServers) {

            // Loop through each database server for this name
            foreach ($dbServers as $dbId => $dbOptions) {

                if (is_integer($dbId)) {

                    if (isset($dbOptions['master']) && $dbOptions['master'] !== false) {
                        $dbName .= '_master';
                    }

                    $resource  = new Zend_Application_Resource_Db($dbOptions);
                    $resource->init();
                    $this->addDbAdapter($dbName, $resource->getDbAdapter());

                } else {

                    if (isset($dbServers['master']) && $dbServers['master'] !== false) {
                        $dbName .= '_master';
                    }

                    $resource  = new Zend_Application_Resource_Db($dbServers);
                    $resource->init();
                    $this->addDbAdapter($dbName, $resource->getDbAdapter());
                    break;

                }

            }

        }

        return $this->getDbAdapters();
    }
}
